import { View, Text } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState, useEffect, useMemo, useRef } from 'react'
import styles from './index.module.scss'
import Header from '@/pages/myComponent/header'
// import LgNavCustomBar from '../../components/navCustomBar'
import Search from './search'
import useDebounceValue from './useDebounceValue'
import './index.scss';
// import { LgEmpty } from 'lancoo-ui-mobile'

interface SearchPageCompProps {
  /** 搜索显隐 */
  visible: boolean
  /** 列表数据 */
  dataList?: any[]
  /** 搜索防抖时间 m默认500ms*/
  delay?: number
  /** 页面标题 用于关闭当前组件回复原先 */
  title?: string
  /** 设置列表数据 */
  setDataList?(dataList: any[]): void
  /** 数据是否加载 */
  loading: boolean
  /** 列表JSX */
  childrenDom: JSX.Element[] | JSX.Element
  placeholder: string,
  /** 设置显隐属性 */
  setVisible(visible: boolean): void
  /** 设置关键词 */
  setWords(word: string): void
}

function SearchPageComp(props: SearchPageCompProps) {
  const {
    visible = false,
    loading,
    title = '',
    delay = 500,
    dataList = [],
    childrenDom,
    placeholder,
    setDataList,
    setVisible,
    setWords,
  } = props
  const [keyword, setKeyword] = useState('')
  const [focus, setFocus] = useState(false)
  const debounceKeyword = useDebounceValue(keyword, delay)

  const [history, setHistory] = useState<Array<string>>([])

  useEffect(() => {
    if (!debounceKeyword) return
    setWords(debounceKeyword)
    //设置历史记录
    const index = history.findIndex(c => c === debounceKeyword)
    if (index === -1 && debounceKeyword) {
      const filterHistory = history.concat(debounceKeyword)
      setHistory(filterHistory)
    }
  }, [debounceKeyword])

  const handleClose = () => {
    setVisible(false)
    setKeyword('')
    setWords('')
    if (title) document.title = title
    // Taro.eventCenter.trigger('refreshMyApply')
  }

  //是否显示历史记录 党非加载状态且未输入关键词
  const historyVisible = !loading && !keyword && history.length > 0
  console.log(loading)
  console.log(keyword)
  console.log(history)
  //是否展示空状态 非加载 且 数据为空 且有搜索关键词
  const emptyVisible = loading || (dataList.length <= 0 && keyword)

  //点击历史记录进行搜索
  const handleClickHistory = h => {
    setKeyword(h)
    setWords(h)
  }

  //清除历史记录
  const handleClearHistory = () => {
    Taro.showModal({
      title: '提示',
      content: '是否清空历史记录？',
      confirmColor: '#0099ff',
      success: function (res) {
        if (res.confirm) {
          setHistory([])
          setDataList && setDataList([])
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      },
    })
  }

  const content = useMemo(() => {
    if (historyVisible) {
      return (
        <View className={styles.history}>
          <View className={styles['history-nav']}>
            <View className={styles['history-nav-left']}>搜索记录</View>
            <View className={styles['history-nav-right']} onClick={handleClearHistory}></View>
          </View>
          <View className={styles['history-content']}>
            {history.map((h, index) => {
              if (!h) return null
              return (
                <View
                  onClick={() => handleClickHistory(h)}
                  key={index}
                  className={styles['history-item']}
                >
                  {h}
                </View>
              )
            })}
          </View>
        </View>
      )
    }
    if (dataList.length) {
      return <View className={styles.wrapper}>{childrenDom}</View>
    }
    return (
      <View className={styles.empty}>
        <div className='emptyBox'>
          <div className='emptyImg'>
          </div>
          <div className='text'>
            {keyword ? `未搜索到“${keyword}”相关内容` : '输入关键词即可搜索'}
          </div>
        </div>
        {/* <LgEmpty type='file'>
          {debounceKeyword ? `未搜索到“${debounceKeyword}”相关内容` : '输入关键词即可搜索'}
        </LgEmpty> */}
      </View>
    )
  }, [childrenDom, historyVisible, emptyVisible])

  useEffect(() => {
    if (visible) {
      setTimeout(() => {
        setFocus(true)
      }, 500)
    } else {
      setFocus(false)
    }
  }, [visible])

  const isWeapp = getSystemInfo() === 'weapp'

  return (
    <View style={{ display: visible ? "inherit" : "none" }} className={styles.container}>
      {/* <Header title='搜索' needHome={false} isBlod={false} isLeft goback={handleClose} /> */}
      <Header
        title='搜索'
        goback={handleClose}
      />
      {/* <LgNavCustomBar
        mainTitle={'搜索'}
        needMainIcon={process.env.TARO_ENV === "h5" ? true : false}
        needBackIcon={true}
        isTitlePositionLeft={true}
        mainTitleBold={false}
        onClick={handleClose}
        // goBackPage={handleClose}
      ></LgNavCustomBar> */}
      {isWeapp && (
        <View className={styles.tip}>
          小程序状态下点击返回将退出到校园通首页，若想回到上一页请点击取消按钮
        </View>
      )}
      <View className={styles.search}>
        <Search
          value={keyword}
          onInput={setKeyword}
          focus={focus}
          className={styles.ipt}
          placeholder={placeholder}
          onClose={() => {
            setKeyword('')
            setWords('')
            setDataList && setDataList([])
          }}
        />
        {isWeapp && (
          <View className={styles.cancel} onClick={handleClose}>
            取消
          </View>
        )}
      </View>
      {content}
    </View>
  )
}
export default SearchPageComp

function getQueryVariable(variable) {
  if (process.env.TARO_ENV === 'h5') {
    let query =
      window.location.search.substring(1) ||
      window.location.href.split('?')[1] ||
      window.location.href
    // console.log(query)
    let vars = query.split('&')
    for (let i = 0; i < vars.length; i++) {
      let pair = vars[i].split('=')
      if (pair[0] === variable) {
        return decodeURI(pair[1])
      }
    }
    return false
  } else if (process.env.TARO_ENV === 'weapp') {
    let RouterParmas = Taro.getCurrentInstance().router?.params
    if (!RouterParmas) return undefined
    return RouterParmas[variable] || undefined
  }
}

function getSystemInfo() {
  //获取当前系统环境嵌入小程序/h5页面
  if (
    // window.__wxjs_environment === 'miniprogram' ||
    getQueryVariable('env') === 'weapp' ||
    process.env.TARO_ENV === 'weapp'
  ) {
    return 'weapp'
  } else {
    return 'h5'
  }
}
